var roleManage = function() {

    var _init = function() {

        var table = $('#table_role');

        table.dataTable({
            "processing": true,
            // 开启服务器模式
            serverSide: true,
            "ajax": {
                //url: "/a/sys/roles", // 列表查询
            	url:url+"s",
                // data: json
            },
            "autoWidth": false,
            "columns": [{
                "width": "15%",
                "data": "id"
            },{
                "width": "15%",
                "data": "title"
            },{
                "width": "10%",
                "data": "status"
            },
            {
                "width": "10%",
                "data": "author"
            },{
                    "width": "20%",
                    "data": "createDate"
                },
                {
                    "width": "20%",
                    "data": "createDate"
                },
                {
                    "width": "10%",
                    "data": "null",
                    "defaultContent": "<button type=\"button\" class=\"btn blue btn_edit_role\">修改</button><button type=\"button\" class=\"btn red btn_del_role\">删除</button>"
                }
            ],
            "language": {
                "lengthMenu": "每页显示 _MENU_ 条记录",
                "emptyTable": "暂无数据记录",
                "info": "显示 _START_ 至 _END_ 条数据，共 _TOTAL_ 条记录！",
                "zeroRecords": "没有搜索到匹配记录",
                "infoEmpty": "",
                "infoFiltered": "",
                "processing": "数据加载中,请稍后..."
            },
            "pageLength": 5,
            "order": [
                [5, "desc"]
            ],
            "columnDefs": [{
                "orderable": false,
                "targets": [0, 6]
            },  {
                "targets": 1,
                "render": function(data, type, row, meta) {
                     // return data+"  <a href=\" onclick=\"viewArticle('"+data.id+"',event)\"> <i class=\"fa fa-lg-2 fa-file-o \"></a>";
                      return  "<a href='#' >"+data+"</a>"
                }
            },{
                "targets": 4,
                "render": function(data, type, row, meta) {
                    return moment(data).format('YYYY-MM-DD HH:mm');
                }
            }, {
                "targets": 5,
                "render": function(data, type, row, meta) {
                    return moment(data).format('YYYY-MM-DD HH:mm');
                }
            }],
            "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'row'<'col-md-5'i><'col-md-7'>p>",
            "fnInitComplete": function() {}
        });

        // 关闭弹框
        $(".modal").on('hidden.bs.modal', function(e) {
            $('.modal .alert').css('display', 'none'); // 隐藏提示头
            $('.modal .form-group').removeClass('has-error'); //清除错误信息
            $('.modal input[type="text"]').val(''); // 清空 input
            $('.modal input[type="checkbox"]').prop('checked', false); // 清空 input
        });
        // 添加
        $('#btn_new_role').click(function(event) {
//            $('#modal_new_role').modal('show');
        	window.location.href="/p/wxconf/article/eidt?id=null"; 
        });
        // 取消
        $('#btn_cancle').click(function(event) {
        	window.location.href="/p/wxconf/article";
        });
        $("#table_role").on("click","tr td:nth-child(2)",function(){//给tr或者td添加click事件
        	 var name = $(this).text();
        	    alert(name);
        	    var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象

            var _id = oData_arr[0].id;
        	    window.location.href="/p/wxconf/article/detail?id="+_id; 
      });
        function viewArticle(id,a){
        	alert(id);
        	
        }
		// 确定添加
		$('#modal_sure_new').click(function() {
			var title = $('#modal_new_role [name="input_title"]').val();
			var titleAlign=$('#modal_new_role input:radio[name="titleAlign"]:checked').val();
			var author = $('#modal_new_role [name="input_author"]').val();
			var status=$('#modal_new_role input:radio[name="status"]:checked').val();
			var summary = $('#modal_new_role [name="input_summary"]').val();
			var iconUrl = $('#btn-uploader [name="input_qiniu_url"]').val();

			var detail= $('#modal_new_role [name="input_detail"]').val();
			var id = $('#modal_new_role [type="hidden"]').val();
//			var roleId = $('#modal_new_role [name="input_roleId"]').val();
			var param={"article":{"title":title,"titleAlign":titleAlign,"author":author,"status":status,"summary":summary,"id":id,"iconUrl":iconUrl},"detail":detail}
			if (!validate(title, 'require')) {
				$('#modal_new_role .help-block').html('请填写文章标题'); 
				return;
			}/*if (!validate(titleAlign, 'require')) {
				$('#modal_new_role .help-block').html('请选择位置');
				return;
			}*/if (!validate(author, 'require')) {
				$('#modal_new_role .help-block').html('填写作者');
				return;
			}if (!validate(summary, 'require')) {
				$('#modal_new_role .help-block').html('请输入摘要');
				return;
			}if (!validate(detail, 'require')) {
				$('#modal_new_role .help-block').html('请输入内容');
				return;
			}/*if (!validate(roleId, 'require')) {
				$('#modal_new_role .help-block').html('请填写角色');
				return;
			}if (!validate(phone, 'phone')) {
				$('#modal_new_role .help-block').html('电话格式不正确，请修改');
				return;
			}*/ else {
				var _type = id == null||id == '' ? "put" : "post";

				$.ajax({
					url : '/a/wxconf/article',
					type : _type,
					dataType : 'json',
					contentType:"application/json; charset=utf-8",
					data : JSON.stringify(param),
				}).done(function(data) {
					if (data.status === '1') {
						// 正确
//						window.location.reload();
			        	window.location.href="/p/wxconf/article";

//						$('#modal_new_role').modal('hide');
					} else if (data.status === '2') {
//						错误
						$('#modal_new_role .help-block').html(data.msg); // 返回错误信息
					}
				});
			}
		});
		
		
		// 表单验证
		function validate(value, type) {
			// 字段值
			var value = $.trim(value);

			// 非空验证
			if (type === 'require') {
				return !!value;
			}
			// 手机号验证
			if (type === 'phone') {
				return /^1\d{10}$/.test(value);
			}
			// 邮箱验证
			if (type === 'email') {
				return /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/.test(value);
			}
		}
		;
        
        // 修改
        table.on('click', '.btn_edit_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象

            var _id = oData_arr[0].id;
        	window.location.href="/p/wxconf/article/eidt?id="+_id; 
        });

        // 删除
        table.on('click', '.btn_del_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象
            var _id = oData_arr[0].id;
            bootbox.dialog({
                message: "确定要删除",
                title: "提示",
                buttons: {
                    cancel: {
                        label: "取消",
                        className: "btn dark btn-outline"
                    },
                    success: {
                        label: "确定",
                        className: "btn green",
                        callback: function() {
                            // alert('提交删除');
                            var _data = JSON.stringify({ id: _id });
                            request_role_del(_data, function(res) {
                                // 正确
                                table.DataTable().ajax.reload();
                            }, function(err) {
                                //	错误
                                alert(err);
                            })
                        }
                    }
                }
            });
        });
    }

    return {
        init: function() {
            _init();
        }

    };

}();

var roleForm = function() {

    // 新建表单验证
    var validate_role_new = function() {

        var form_new = $('#form_role_new');
        var error_new = $('.alert-danger', form_new);
        var success_new = $('.alert-success', form_new);
        var server_error_new = $('.alert-warning', form_new);

        form_new.validate({
            errorElement: 'span',
            errorClass: 'help-block help-block-error',
            focusInvalid: false,
            ignore: "", // 不验证隐藏input
            rules: {
                name: {
                    required: true
                },
                relaIds: {
                    required: true
                }
            },
            messages: {
                name: {
                    required: "请填写角色名称"
                },
                relaIds: {
                    required: "请选择角色"
                }
            },

            errorPlacement: function(error, element) {
                if (element.parent(".input-group").size() > 0) {
                    error.insertAfter(element.parent(".input-group"));
                } else if (element.attr("data-error-container")) {
                    error.appendTo(element.attr("data-error-container"));
                } else if (element.parents('.radio-list').size() > 0) {
                    error.appendTo(element.parents('.radio-list').attr("data-error-container"));
                } else if (element.parents('.radio-inline').size() > 0) {
                    error.appendTo(element.parents('.radio-inline').attr("data-error-container"));
                } else if (element.parents('.checkbox-list').size() > 0) {
                    error.appendTo(element.parents('.checkbox-list').attr("data-error-container"));
                } else if (element.parents('.checkbox-inline').size() > 0) {
                    error.appendTo(element.parents('.checkbox-inline').attr("data-error-container"));
                } else {
                    error.insertAfter(element);
                }
            },

            invalidHandler: function(event, validator) {
                success_new.hide();
                server_error_new.hide();
                error_new.show();
            },

            highlight: function(element) {
                $(element)
                    .closest('.form-group').addClass('has-error');
            },

            unhighlight: function(element) {
                $(element)
                    .closest('.form-group').removeClass('has-error');
            },

            success: function(label) {
                label
                    .closest('.form-group').removeClass('has-error');
            },

            submitHandler: function(form) {
                success_new.show();
                error_new.hide();
                server_error_new.hide();
                $(form).find('button[type=submit]').attr('disabled', 'disabled');

                var _data = JSON.stringify($(form).serializeObject());

                request_role_new(_data, function(res) {
                    // 正确
                    $("#table_role").DataTable().ajax.reload(); // 刷新table
                    $('#modal_new_role').modal('hide');
                    $(form).find('button[type=submit]').removeAttr('disabled');                    
                }, function(err) {
                    //	错误
                    success_new.hide();
                    server_error_new.show();
                    server_error_new.html(err);
                    $(form).find('button[type=submit]').removeAttr('disabled');
                })

                return false;
            }
        });
    }

    // 编辑表单验证
    var validate_role_edit = function() {

        var form_edit = $('#form_role_edit');
        var error_edit = $('.alert-danger', form_edit);
        var success_edit = $('.alert-success', form_edit);
        var server_error_edit = $('.alert-warning', form_edit);

        form_edit.validate({
            errorElement: 'span',
            errorClass: 'help-block help-block-error',
            focusInvalid: false,
            ignore: "", // 不验证隐藏input
            rules: {
                name: {
                    required: true
                },
                relaIds: {
                    required: true
                }
            },
            messages: {
                name: {
                    required: "请填写角色名称"
                },
                relaIds: {
                    required: "请选择角色"
                }
            },

            errorPlacement: function(error, element) {
                if (element.parent(".input-group").size() > 0) {
                    error.insertAfter(element.parent(".input-group"));
                } else if (element.attr("data-error-container")) {
                    error.appendTo(element.attr("data-error-container"));
                } else if (element.parents('.radio-list').size() > 0) {
                    error.appendTo(element.parents('.radio-list').attr("data-error-container"));
                } else if (element.parents('.radio-inline').size() > 0) {
                    error.appendTo(element.parents('.radio-inline').attr("data-error-container"));
                } else if (element.parents('.checkbox-list').size() > 0) {
                    error.appendTo(element.parents('.checkbox-list').attr("data-error-container"));
                } else if (element.parents('.checkbox-inline').size() > 0) {
                    error.appendTo(element.parents('.checkbox-inline').attr("data-error-container"));
                } else {
                    error.insertAfter(element);
                }
            },

            invalidHandler: function(event, validator) {
                success_edit.hide();
                server_error_edit.hide();
                error_edit.show();
            },

            highlight: function(element) {
                $(element)
                    .closest('.form-group').addClass('has-error');
            },

            unhighlight: function(element) {
                $(element)
                    .closest('.form-group').removeClass('has-error');
            },

            success: function(label) {
                label
                    .closest('.form-group').removeClass('has-error');
            },

            submitHandler: function(form) {
                success_edit.show();
                error_edit.hide();
                server_error_edit.hide();
                $(form).find('button[type=submit]').attr('disabled', 'disabled');

                var _data = JSON.stringify($(form).serializeObject());

                request_role_edit(_data, function(res) {
                    // 正确
                    $("#table_role").DataTable().ajax.reload(); // 刷新table
                    $('#modal_edit_role').modal('hide');
                    $(form).find('button[type=submit]').removeAttr('disabled');
                    
                }, function(err) {
                    //	错误
                    success_new.hide();
                    server_error_new.show();
                    server_error_new.html(err);
                    $(form).find('button[type=submit]').removeAttr('disabled');
                })

                return false;
            }
        });
    }

    return {
        init: function() {
            validate_role_new();
            validate_role_edit();
        }

    };
}();

$(function() {
    roleManage.init();
    roleForm.init();
});